﻿using Aspose.Cells;
using FlowCard.PrintCard.Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlowCard.PrintCard.Helper
{
    internal class FileHelper
    {
        /// <summary>
        /// 导出为PDF
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileNamepd"></param>
        //旧用法
        //String[] files = new String[] { fileNamepdf,fileNamepdf2
        //        };
        //PdfDocumentBase doc = PdfDocument.MergeFiles(files);
        //doc.Save(fileNamepdf3, Spire.Pdf.FileFormat.PDF);
        protected internal static void CovertoPdf(string filePath, string fileNamepd)
        {
            string excelFilePath = filePath;
            Workbook workbook = new Workbook(excelFilePath);

            // 导出为PDF
            string pdfFilePath = fileNamepd;
            workbook.Save(pdfFilePath, SaveFormat.Pdf);
            ////创建一个Workbook对象
            //Workbook workbook = new Workbook();

            ////加载示例 Excel 文档
            //workbook.LoadFromFile(filePath);

            ////转换时将工作表设置为适应页面
            //workbook.ConverterSetting.SheetFitToPage = true;

            ////获取特定的工作表
            //Worksheet worksheet = workbook.Worksheets[0];

            ////保存为PDF文件
            //worksheet.SaveToPdf(fileNamepd);

        }

        /// <summary>
        /// 合并PDF（直接拼接，不改变文件的尺寸、样式）
        /// </summary>
        /// <param name="files">需要合并的pdf的绝对路径集合（D:\test1.pdf）</param>
        /// <param name="saveFileName">保存合并文件的绝对路径（D:\merge.pdf）</param>
        protected internal static void MergePdf(List<string> files, string saveFileName)
        {
            Document doc = new Document();
            PdfCopy pdfCopy = new PdfCopy(doc, new FileStream(saveFileName, FileMode.Create));
            try
            {
                doc.Open();
                for (int i = 0; i < files.Count; i++)
                {
                    PdfReader reader = new PdfReader(files[i]);
                    int pageNum = reader.NumberOfPages;
                    for (int j = 1; j <= pageNum; j++)
                    {
                        PdfImportedPage importPage = pdfCopy.GetImportedPage(reader, j);
                        pdfCopy.AddPage(importPage);
                    }
                    reader.Close();
                }
                doc.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                doc.Close();
            }
        }
        /// <summary>
        /// 将多个excel文件合并成一个
        /// </summary>
        /// <param name="files">excel文件路径集合</param>
        /// <param name="saveFileName">合并后的文件保存完整路径</param>
        /// <param name="IsDeleteTemp">是否删除临时文件</param>
        protected internal static void MergeExcel(Dictionary<string, string> files, string saveFileName)
        {
            // 确保目标文件是新的或已存在
            FileInfo destinationFileInfo = new FileInfo(saveFileName);
            if (destinationFileInfo.Exists)
            {
                destinationFileInfo.Delete(); // 删除现有文件以便后续创建
            }

            using (ExcelPackage destinationPackage = new ExcelPackage())
            {
                // 遍历每个Excel文件
                foreach (var file in files.Where(a => Path.GetExtension(a.Value).ToLower() == ".xlsx" || Path.GetExtension(a.Value).ToLower() == ".xls"))
                {
                    FileInfo existingFile = new FileInfo(file.Value);
                    if (existingFile.Exists)
                    {
                        using (ExcelPackage sourcePackage = new ExcelPackage(existingFile))
                        {
                            // 获取第一个工作表
                            ExcelWorksheet sourceWorksheet = sourcePackage.Workbook.Worksheets[0];

                            // 创建副本，并命名为原始工作表名称
                            string newWorksheetName = file.Key;
                            ExcelWorksheet newWorksheet = destinationPackage.Workbook.Worksheets.Add(newWorksheetName, sourceWorksheet);
                        }
                    }
                }
                // 保存目标文件
                destinationPackage.SaveAs(destinationFileInfo);
            }
        }
        /// <summary>
        /// 重新渲染pdf
        /// </summary>
        /// <param name="resourcePdfPath">源文件名</param>
        /// <param name="savePdfPath">新文件名</param>
        protected internal static void AddImgToPDF(string resourcePdfPath, string savePdfPath, string imagePath)
        {
            //加载源文件
            PdfReader reader = new PdfReader(resourcePdfPath);
            PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(savePdfPath, FileMode.Create));
            int iPageNum = reader.NumberOfPages; //pdf页面数
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            //加载图片
            Image img = Image.GetInstance(imagePath);
            //设置图片位置
            img.SetAbsolutePosition(0, 580);
            //对pdf每页进行填充
            for (int j = 1; j <= iPageNum; j++)
            {
                PdfContentByte over = pdfStamper.GetOverContent(j);
                over.AddImage(img);
            }
            pdfStamper.Close();
            reader.Close();
        }

        /// <summary>
        /// 重新渲染pdf
        /// </summary>
        /// <param name="resourcePdfPath"></param>
        /// <param name="savePdfPath"></param>
        protected internal static void AddImgToPDF(string resourcePdfPath, string savePdfPath, int X, int Y, string imagePath)
        {
            //加载临时文件
            PdfReader reader = new PdfReader(resourcePdfPath);
            PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(savePdfPath, FileMode.Create));
            int iPageNum = reader.NumberOfPages; //pdf页面数
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            //加载图片
            Image img = Image.GetInstance(imagePath);
            //设置图片位置
            img.SetAbsolutePosition(X, Y);
            //对pdf每页进行填充
            for (int j = 1; j <= iPageNum; j++)
            {
                PdfContentByte over = pdfStamper.GetOverContent(j);
                over.AddImage(img);
            }
            pdfStamper.Close();
            reader.Close();
        }

        /// <summary>
        /// 重新渲染pdf
        /// </summary>
        /// <param name="resourcePdfPath">源文件临时文件路径</param>
        /// <param name="savePdfPath">最终的文件路径</param>
        /// <param name="imgepath">二维码临时路径</param>
        /// <param name="QRSize">二维码大小</param>
        /// <param name="X">二维码水平位置</param>
        /// <param name="Y">二维码纵向位置</param>
        protected internal static void AddImgToPDF(string resourcePdfPath, string savePdfPath, string imgepath, int QRSize, int X, int Y)
        {
            //加载临时文件
            PdfReader reader = new PdfReader(resourcePdfPath);
            PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(savePdfPath, FileMode.Create));
            int iPageNum = reader.NumberOfPages; //pdf页面数
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            string imagePath = imgepath;
            //加载图片
            Image img = Image.GetInstance(imagePath);

            img.ScaleAbsolute(QRSize, QRSize);
            //设置图片位置
            img.SetAbsolutePosition(X, Y);
            //对pdf每页进行填充
            for (int j = 1; j <= iPageNum; j++)
            {
                PdfContentByte over = pdfStamper.GetOverContent(j);
                over.AddImage(img);
            }
            pdfStamper.Close();
            reader.Close();
            File.Delete(resourcePdfPath);
        }
        /// <summary>
        /// 删除文件夹内的所有文件，忽略指定文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="ignore"></param>
        protected internal static void DeleteFile(string path, params string[] ignore)
        {
            // 获取目录中所有文件
            string[] files = Directory.GetFiles(path);

            foreach (string file in files)
            {
                // 排除特定文件
                if (!ignore.Contains(file) && !ignore.Contains(Path.GetFileName(file)))
                {
                    try
                    {
                        // 删除文件
                        File.Delete(file);
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
            }
        }
    }
}
